﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Hangfire;
using StackExchange.Redis;
using Hangfire.Redis;
using NLog;
using NLog.Extensions.Logging;
using NLog.Web;
using HangfireLog.Model;

namespace HangfireLog
{
    public class Startup
    {
        public static ConnectionMultiplexer Redis;
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            Redis = ConnectionMultiplexer.Connect("localhost:6379,password=123456");

        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(config =>
            {
                config.UseNLogLogProvider();
                config.UseRedisStorage(Redis, new RedisStorageOptions() { Prefix = "hangfireLogTest:" });
            });
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseDeveloperExceptionPage();

            env.ConfigureNLog("nlog.config");
            loggerFactory.AddNLog();
            app.AddNLogWeb();

            app.UseHangfireDashboard();
            app.UseHangfireServer(new BackgroundJobServerOptions()
            {
                ServerName = "mac"
            });

            app.UseMvc();

            var jobId = "helloJob";
            RecurringJob.RemoveIfExists(jobId);
            RecurringJob.AddOrUpdate(jobId, () => TestMethod(), Cron.Minutely(), TimeZoneInfo.Local);
        }

        [AutomaticRetry(Attempts = 1)]
        public async Task TestMethod()
        {
            await Task.Run(() =>
            {
                // throw new Exception("测试的，会写出来么");
                throw new BizException("时间不对");
            });
        }
    }
}
